//
//  HJSelectFridendsController.m
//  KaiChat
//
//  Created by lx on 2023/11/2.
//

#import "HJSelectFridendsController.h"
#import "HJSelectFridendCell.h"
#import "HJSectionHeaderView.h"
#import "HJFriendListHeaderButton.h"
#import "HJIM.h"
#import "HJUserInfoController.h"
#import "QMUITextField.h"
#import "HJAddFriendController.h"
#import "HJNavigationController.h"
#import "HJSelectMemberView.h"
#import "HJChatController.h"
#import "HJChatGroupModel.h"
#import "HJSelectFridendsSearchController.h"

@interface HJSelectFridendsController ()

@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, strong) NSMutableArray *sortKeys;
@property (nonatomic, strong) NSMutableArray *selectDatas;
@property (nonatomic, strong) NSMutableArray *originalDatas;

@property (nonatomic, weak) HJSelectMemberView *selectMemberView;
@property (nonatomic, weak) HJBarButton *doneButton;
@property (nonatomic, weak) UIView *searchView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, assign) NSInteger lastCount;

@end

@implementation HJSelectFridendsController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    HJBarButton *doneButton = [HJBarButton barButtonWithTitle:@"Done" color:UIColor.tj_mainColor target:self action:@selector(didClickDoneButton:)];
    doneButton.enabled = NO;
    [doneButton setTitleColor:UIColor.tj_mainColor forState:UIControlStateNormal];
    [doneButton setTitleColor:UIColor.tj_BEBDCAColor forState:UIControlStateDisabled];
    [self.navigationBar.contentView addSubview:doneButton];
    [doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(leftRightMargin);
        make.width.offset(40);
        make.centerY.offset(0);
        make.height.offset(40);
    }];
    _doneButton = doneButton;
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 60)];
    headerView.backgroundColor = UIColor.whiteColor;
    
    UIView *searchView = [UIView addToView:headerView];
    searchView.backgroundColor = UIColor.tj_F6F6F6Color;
    searchView.addCornerRadius(10);
    [searchView addTapGesturesWithTarget:self action:@selector(tapSearchView)];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.offset(10);
        make.height.offset(40);
    }];
    
    UIImageView *searchIcon = [UIImageView addToView:searchView];
    searchIcon.image = [UIImage imageNamed:@"search_icon"];
    [searchIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(15);
    }];
    
    UILabel *searchTextLabel = [UILabel lableWithSuperView:searchView font:UIFontMake(14) color:UIColor.tj_BEBDCAColor title:@"search" textAlignment:NSTextAlignmentLeft];
    [searchTextLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(searchIcon.mas_right).offset(10);
        make.centerY.offset(0);
    }];
    
    TJWeakify(self)
    HJSelectMemberView *selectMemberView = [HJSelectMemberView addToView:headerView];
    [selectMemberView setDidClickDeleteButtonBlock:^(HJChatFriendModel * _Nonnull model) {
        [weakself didSelectRowWithModel:model];
    }];
    [selectMemberView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.offset(0);
        make.top.equalTo(searchView.mas_bottom).offset(10);
    }];
    
    _headerView = headerView;
    _selectMemberView = selectMemberView;
    _searchView = searchView;
    
    self.navigationBar.title = @"Address book";
    self.view.backgroundColor = UIColor.tj_F6F6F6Color;
    self.tableViewStyle = UITableViewStylePlain;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, TabbarSafeBottomMargin, 0);
    self.tableView.tableHeaderView = headerView;
    [self.tableView registerClass:HJSelectFridendCell.class forCellReuseIdentifier:@"HJSelectFridendCell"];
    [self.tableView registerClass:HJSectionHeaderView.class forHeaderFooterViewReuseIdentifier:@"HJSectionHeaderView"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 64;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView setSectionIndexColor:UIColor.tj_333333Color];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight);
        make.left.right.bottom.offset(0);
    }];
    [self loadData];
}

- (void)didClickDoneButton:(UIButton *)button {
    
    [HJHUD showLoadingInView:self.view];
    
    NSMutableArray *array = [NSMutableArray array];
    for (HJChatFriendModel *model in self.selectDatas) {
        [array addObject:model.userId];
    }
    [HJIM.shareIM.groupManager createGroupByGroupIdWithUserIds:array completion:^(HJChatGroupModel * _Nullable groupModel) {
        
        if (groupModel) {
            
            [self dismissToRootViewController:YES completion:^{
                
                HJChatController *chatController = [HJChatController chatControllerWithSessionModel:[HJChatSessionModel modelWithBlock:^(HJChatSessionModel * _Nonnull model) {
                    model.sessionId = toString(groupModel.groupId);
                    model.sessionName = groupModel.name;
                    model.chatType = HJChatTypeGroup;
                }]];
                [[HJTools currentNavController] pushViewController:chatController];
            }];
        }
    }];
}

- (void)didClickNewFriendButton {
    [self.navigationController pushViewControllerWithName:@"HJApplyListController"];
}

- (void)tapSearchView {
    HJSelectFridendsSearchController *selectFridendsSearchController = [[HJSelectFridendsSearchController alloc] init];
    selectFridendsSearchController.selectDatas = self.selectDatas;
    selectFridendsSearchController.datas = self.originalDatas;
    TJWeakify(self)
    [selectFridendsSearchController setSelectComplete:^{
        [weakself.tableView reloadData];
        [weakself updateDoneTitle];
        [weakself updateSelectMemberViewHeight];
    }];
    HJNavigationController *navController = [[HJNavigationController alloc] initWithRootViewController:selectFridendsSearchController];
    [self presentViewController:navController animated:YES completion:nil];
}


- (void)selectFridendsSearchControllerDidDelete:(HJSelectFridendsSearchController *)controller {
    
}

- (nullable HJSelectFridendCell *)getVisibleCellWithModel:(HJChatFriendModel *)model {
    for (HJSelectFridendCell *cell in self.tableView.visibleCells) {
        if (cell.model == model) {
            return cell;
        }
    }
    return nil;
}

- (void)selectFridendsSearchControllerDidSelectCell:(HJSelectFridendsSearchController *)controller model:(HJChatFriendModel *)model {
    [self didSelectRowWithModel:model];
}

- (void)loadData {
    [[HJIM shareIM].userManager getFriendListsComplete:^(NSArray<HJChatFriendModel *> * _Nullable datas) {
        dispatch_async_main_queue(^{
            [self hiddenLoading];
            [self handleModels:datas];
        });
    }];
}

- (void)updateSelectState:(HJChatFriendModel *)obj {
    if (self.selectDatas.count == 0) return;
    
    for (HJChatFriendModel *model in self.selectDatas) {
        if ([obj.userId isEqualToString:model.userId]) {
            obj.isSelect = model.isSelect;
            break;
        }
    }
}

- (void)handleModels:(NSArray *)models {
    
    [self.originalDatas removeAllObjects];
    
    NSMutableDictionary *mainDict = [NSMutableDictionary dictionary];
    for (HJChatFriendModel *obj in models) {
        
        if (TJIM_isSelf(obj.userId)) {
            continue;
        }
        
        [self.originalDatas addObject:obj];
        [self updateSelectState:obj];
        
        NSString *displayName = obj.showName;
        NSString *firstLetter = [displayName.firstPinYin uppercaseString];
        if (firstLetter.length == 0 || !isalpha([firstLetter characterAtIndex:0])) {
            firstLetter = @"#";
        }
        NSMutableArray *dictMarr = [mainDict valueForKey:firstLetter];
        if (!dictMarr) {
            [mainDict setValue:[NSMutableArray array] forKey:firstLetter];
            dictMarr = [mainDict valueForKey:firstLetter];
        }
        [dictMarr addObject:obj];
    }
    
    NSArray *nonameList = [mainDict valueForKey:@"#"];
    if (nonameList) {
        [mainDict removeObjectForKey:@"#"];
    }
    
    [self.datas removeAllObjects];
    [self.sortKeys removeAllObjects];
    
    NSArray *sortKeys = [mainDict.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString *  _Nonnull obj1, NSString *  _Nonnull obj2) {
        return [obj1 compare:obj2] == NSOrderedDescending;
    }];
 
    [sortKeys enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.datas addObject:@{ @"title": obj, @"datas": mainDict[obj]}];
    }];
    
    self.sortKeys = [NSMutableArray arrayWithArray:sortKeys];
    if (nonameList.count) {
        [self.sortKeys addObject:@"#"];
        [self.datas addObject:@{@"title": @"#", @"datas": nonameList}];
    }
    
    [self.tableView reloadData];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *datas = self.datas[section][@"datas"];
    return [datas count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJSelectFridendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJSelectFridendCell" forIndexPath:indexPath];
    HJChatFriendModel *model = self.datas[indexPath.section][@"datas"][indexPath.row];
    cell.model = model;
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HJChatFriendModel *model = self.datas[indexPath.section][@"datas"][indexPath.row];
    [self didSelectRowWithModel:model];
}

- (void)didSelectRowWithModel:(HJChatFriendModel *)model {
    
    model.isSelect = !model.isSelect;
    
    HJSelectFridendCell *cell = [self getVisibleCellWithModel:model];
    cell.model = model;
    if (model.isSelect) {
        if (![self.selectDatas containsObject:model]) {
            [self.selectDatas addObject:model];
        }
    } else {
        if ([self.selectDatas containsObject:model]) {
            [self.selectDatas removeObject:model];
        }
    }
    
    [self updateDoneTitle];
    [self updateSelectMemberViewHeight];
}


- (void)updateSelectMemberViewHeight {
    if (_lastCount > 0 && self.selectDatas.count > 0) {
        self.lastCount = self.selectDatas.count;
        self.selectMemberView.datas = self.selectDatas;
        return;
    };
    
    [UIView animateWithDuration:0.01 animations:^{
        if (self.selectDatas.count > 0) {
            self.headerView.tj_height = 140;
            self.tableView.tableHeaderView = self.headerView;
            [self.selectMemberView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.offset(0);
                make.height.offset(80);
                make.top.equalTo(self.searchView.mas_bottom).offset(10);
            }];
        } else {
            self.headerView.tj_height = 60;
            self.tableView.tableHeaderView = self.headerView;
            [self.selectMemberView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.offset(0);
                make.height.offset(0);
                make.top.equalTo(self.searchView.mas_bottom).offset(10);
            }];;
        }
    } completion:^(BOOL finished) {
        self.lastCount = self.selectDatas.count;
        self.selectMemberView.datas = self.selectDatas;
    }];
    
    
}

- (void)updateDoneTitle {
    if (self.selectDatas.count > 0) {
        _doneButton.enabled = self.selectDatas.count > 1;
        [_doneButton setTitle:[NSString stringWithFormat:@"Done(%ld)", self.selectDatas.count] forState:UIControlStateNormal];
    } else {
        _doneButton.enabled = NO;
        [_doneButton setTitle:@"Done" forState:UIControlStateNormal];
    }
    [_doneButton sizeToFit];
    CGFloat doneButtonW = MAX(_doneButton.tj_width + 10, 40);
    [_doneButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.offset(doneButtonW);
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
}

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.sortKeys;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    HJSectionHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HJSectionHeaderView"];
    view.titleLabel.text = @"";
    view.contentView.backgroundColor = UIColor.tj_F6F6F6Color;
    view.backgroundColor = UIColor.tj_F6F6F6Color;
    NSString *sectionTitle = self.datas[section][@"title"];
    view.titleLabel.text = sectionTitle;
    view.titleLabel.textColor = UIColor.tj_868391Color;
    view.titleLabel.font = UIFontMake(12);
    return view;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = UIColor.clearColor;
    return view;
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationFullScreen;
}


- (NSMutableArray *)datas {
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

- (NSMutableArray *)sortKeys {
    if (!_sortKeys) {
        _sortKeys = [NSMutableArray array];
    }
    return _sortKeys;
}

- (NSMutableArray *)selectDatas {
    if (!_selectDatas) {
        _selectDatas = [NSMutableArray array];
    }
    return _selectDatas;
}

- (NSMutableArray *)originalDatas {
    if (!_originalDatas) {
        _originalDatas = [NSMutableArray array];
    }
    return _originalDatas;
}
 

@end

